<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 系统用户管理控制器
 * @package App\Http\Controllers\Admin
 */
class SysUserController extends BaseController
{
    private $userSer;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->userSer = new \App\Services\System\User();
    }

    /**
     * 用户列表
     */
    public function index(Request $request)
    {
        $pageSize = $request->get('pageSize', 10);
        //状态条件
        $query = \App\Models\System\User::withTrashed()->select('*')->with('roles');
        $status = $request->input('status', -1);
        if ($status == 1){
            $query->whereNull('deleted_at');
        }else if ($status == 2){
            $query->whereNotNull('deleted_at');
        }
        //名称搜索
        $name = $request->get('name', '');
        $name && $query->where('name', 'like', '%'.$name.'%');
        //邮箱搜索
        $email = $request->get('email');
        $email && $query->where('email','like','%'.$email.'%');

        $query->orderByDesc('id');
        $rows = $query->paginate($pageSize, ['*'], 'pageNo');
        //角色列表数据
        $roleSer = new \App\Services\System\Role();
        $roleList = $roleSer->getRoleList();
        //树结构用户组列表
        $tree          = new \App\Services\Tool\TreeService('role_id', 'parent_id', 'children');
        $tree->load($roleList);
        $treeRoleList = $tree->deepTree();
        return $this->success('加载成功', ['userList' => $rows->items(),'total'=>$rows->total(), 'roleList' => $treeRoleList]);
    }

    /**
     * 新建、编辑保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required_without:id'
        ]);
        try{
            if(!$this->userSer->save($request->toArray())){
                throw new \Exception('保存失败');
            }
            return $this->success('编辑成功');
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }

    /**
     * 禁用用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function disable(Request $request){
        try{
            $userIds = $request->input('user_ids', []);
            if (!empty($userIds) && in_array(1, $userIds)){
                throw new \Exception('超级管理员不允许禁用');
            }
            if(!$this->userSer->changeStatus($userIds, 0)){
                throw new \Exception('保存失败');
            }
            return $this->success('禁用成功');
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }

    /**
     * 激活用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function enable(Request $request){
        try{
            $userId = $request->input('userId', 0);
            if(!$this->userSer->changeStatus($userId, 1)){
                throw new \Exception('保存失败');
            }
            return $this->success('激活成功');
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    /**
     * 重置密码
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function resetPwd(Request $request)
    {
        try {
            $userData = $request->post();
            $userModel = $request->user();

            if (!\Hash::check($userData['password_old'], $userModel->password)) {
                throw new \Exception("原密码不正确！", 5005);
            }

            $validate = \Validator::make($userData, [
                'password' => 'required|string|min:6|confirmed',
            ]);
            if (!empty($validate)) {
                foreach ($validate->errors()->toArray() as $e) {
                    throw new \Exception($e[0], 5005);
                }
            }
            $userModel->password = bcrypt($userData['password']);
            $userModel->save();
            $this->guard()->logout();
            app('request')->session()->invalidate();
            return $this->showMsg('success', '修改密码成功!', [], 'admin.index.index');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
